import React,{useEffect,useRef} from "react";
import { useState } from "react";
import * as Public from "../publicComponents/index"
import {useLocation }from 'react-router-dom'
import  ReactDOM  from "react-dom";
import * as ArcoIcon from "@arco-design/web-react/icon"
import * as Action from "../../common/Action"
import "./common.css"
const TeleportOpeButton=({
    targetNode,
    download,
    close,
    last,
    next
})=>{
    const target=document.querySelector(targetNode)
    return ReactDOM.createPortal(
    <div className="expandedImageContainer">
        <div className="opeButtons">
            {/**下载按钮 */}
            <div className='opeButton' onClick={download} data-name="下载">
                <ArcoIcon.IconDownload style={{color:'var(--colorText-1)',marginTop:0}}></ArcoIcon.IconDownload>
            </div>
            {/**关闭 */}
            <div className='opeButton' onClick={close} data-name="关闭">
                <ArcoIcon.IconClose  style={{color:'var(--colorText-1)',marginTop:0}}></ArcoIcon.IconClose>
            </div>
        </div>
        {/**上一张 */}
        <div className='sideButton' onClick={last} style={{left:'16px'}}>
                <ArcoIcon.IconLeft style={{color:'var(--colorText-1)',marginTop:0}}></ArcoIcon.IconLeft>
            </div>
            {/**下一张 */}
            <div className='sideButton' onClick={next} style={{right:'16px'}}>
                <ArcoIcon.IconRight style={{color:'var(--colorText-1)',marginTop:0}}></ArcoIcon.IconRight>
            </div>
    </div>,
        target
    )
}
export function ImageCollection(props){
    type dataStruct={
        imageList:any[],
        messageList:[],
        showOpeButton:boolean,
        nowViewImage:string,
        nowImageIndex:number,
        position:number[]
    }
    let [data,setData]:[dataStruct,Function]=useState({
        imageList:[],
        messageList:[],
        showOpeButton:false,
        nowViewImage:'',
        nowImageIndex:-1,
        position:[]
    })
    let [messageList,setMessageList]:[any[],Function]=useState([])
    const location=useLocation()
    let stateData=location.state
    let containerRef:any=useRef(null)
    useEffect(()=>{
        //请求数据
        console.log(stateData.collectionID)
        window['netRequest']({
            url:"/getImageCollection",
            method:"POST",
            data:{
                collectionID:stateData.collectionID
            }
        }).then(res=>{
            console.log(res.data)
            try{
                props.setTitle({
                    title:res.data.title,
                    actionType:2,
                    TitleData:{
                        author:'夜月归途',
                        uploadTime:"2023年10月10日",
                        messageNumber:999,
                        viewTimes:999
                    }
                })
            }catch{}
            /*
            for(let i=0;i<res.data.data.length;i++){
                res.data.data[i]=JSON.parse(res.data.data[i])
            }*/
            setData({
                ...data,
                imageList:res.data.data
            })
        }).catch(err=>{
            console.log(err)
        })
        
    },[])
    
    function expandImage(src,index,e){
        let position=e.target.getBoundingClientRect()
        console.log(containerRef.current.childNodes,index)
        let image=containerRef.current.childNodes[index].childNodes[0]//.cloneNode(true)//document.createElement("img")
        image.style.transition='0s'
        image.style.height=position.width+'px'
        image.style.width=position.height+'px'
        image.style.position="fixed"
        image.style.left=(position.x)+'px'
        image.style.top=(position.y)+'px'
        image.style.transform="translate(-50%,-50%)"
        
        setTimeout(()=>{
            image.style.transition=''
            setTimeout(()=>{
                
                image.id='imageExpand'
                image.style.transformOrigin="center"
                image.style.transform=" "
            },50)
            
            image.className="expandedImage"
            //image.src=src
            //document.body.appendChild(image)
            //image.onload=()=>{
            setTimeout(()=>{
                image.style.left=''
                image.style.top=''
                image.style.height='calc(100vmin - 100px)'
                image.style.width=''
                
                image.style.opacity=1
                image.style.transform="translate(-50%,-50%) scale(1)"
            },150)

            //操作按钮
            setData({
                ...data,
                showOpeButton:true,
                nowImageIndex:index,
                nowViewImage:src,
                position:[position.x+position.width/2,position.y+position.height/2,position.width,position.height]
            })
            //}
            
        },60)
        
        
    }
    
    function downloadImage(){
        let a=document.createElement("a")
        a.style.display='none'
        a.setAttribute("href", data.nowViewImage + '?response-content-type=application/octet-stream');
        a.setAttribute("download", 'newFile');
        a.setAttribute("target", "_blank");
        // 使用target="_blank"时，添加rel="noopener noreferrer" 堵住钓鱼安全漏洞 防止新页面window指向之前的页面
        a.rel = "noopener noreferrer";
        document.body.appendChild(a)
        a.click()
        setTimeout(()=>{
            a.remove()
        },500)
    }

    function close(){
        try{    
            let image:any=document.getElementById('imageExpand')
            image.style.cssText=''
            //image.style.transition='0s'
            setTimeout(()=>{
                image.className='imageItem'
                image.removeAttribute("id")
                console.log(image)
            },70)
        }catch{}
        setData({
            ...data,
            showOpeButton:false
        })
    }
    function last(){
        if(data.nowImageIndex<=0){
            Action.Message({
                type:"warn",
                content:"这是第一页"
            })
        }else{
            document.getElementById('imageExpand')?.setAttribute(
                'src',
                data.imageList[data.nowImageIndex-1]
            )
            setData({
                ...data,
                nowImageIndex:data.nowImageIndex-1
            })
        }
    }
    function next(){
        if(data.nowImageIndex>=(data.imageList.length-1)){
            Action.Message({
                type:"warn",
                content:"没图片了"
            })
        }else{
            document.getElementById('imageExpand')?.setAttribute(
                'src',
                data.imageList[data.nowImageIndex+1]
            )
            setData({
                ...data,
                nowImageIndex:data.nowImageIndex+1
            })
        }
    }
    return <>
    <div style={{padding:'20px'}}>
        <Public.Comment background="var(--bg-1)" style={{padding:0,width:'100%'}}>
            
                <Public.TopBar>
                    <div className="topCotainer">首页 / 正文</div>
                </Public.TopBar>
                <div className="imageBordContainer" 
                ref={containerRef}
                style={
                    {backgroundColor:'rgb(var(--gray-1))',
                    marginTop:'20px',
                    marginBottom:'16px',
                    padding:'30px',
                    paddingTop:'40px',
                    width:"calc(100% - 60px)"
                }}>
                    {
                        data.imageList.map((imageItem,index)=>{
                            return  <div style={{width:'100%',position:'relative',height: '180px'}}>
                                        <div className="imageItem">
                                            <img className="image" onClick={(e)=>{expandImage(imageItem,index,e)}} src={imageItem}/>
                                        </div>
                                    </div>
                        })
                    }
                </div>
            <div className="pageChange">
                <div className="pageChangeButton" style={{left:0}}>上一篇</div>
                <div className="pageChangeButton" style={{right:0}}>下一篇</div>
            </div>
        </Public.Comment>
        </div>
        {/**图片操作按钮 */}
        {
            data.showOpeButton?<TeleportOpeButton 
                download={downloadImage}
                close={close}
                last={last}
                next={next}
            targetNode="body"/>:null
        }
        </>
}
